"""
启动脚本
"""
import os
import sys
import subprocess
import argparse
from pathlib import Path

# 添加项目路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))


def run_api_server():
    """启动API服务器"""
    print("启动API服务器...")
    
    from core.config import get_settings
    settings = get_settings()
    
    cmd = [
        sys.executable, "-m", "uvicorn",
        "main:app",
        "--host", settings.host,
        "--port", str(settings.web_port),
        "--reload" if settings.debug else "",
        "--log-level", settings.log_level.lower()
    ]
    
    cmd = [c for c in cmd if c]  # 移除空字符串
    
    subprocess.run(cmd)


def run_mcp_server():
    """启动MCP服务器"""
    print("启动MCP服务器...")
    
    from core.config import get_settings
    settings = get_settings()
    
    cmd = [sys.executable, "mcp_server/server.py"]
    env = os.environ.copy()
    env['MCP_PORT'] = str(settings.mcp_port)
    
    print(f"MCP服务器将在 http://{settings.host}:{settings.mcp_port} 启动")
    subprocess.run(cmd, env=env)


def run_init():
    """运行初始化"""
    print("运行系统初始化...")
    subprocess.run([sys.executable, "init_db.py"])


def run_tests():
    """运行测试"""
    print("运行测试...")
    subprocess.run([sys.executable, "-m", "pytest", "tests/", "-v"])


def run_format():
    """格式化代码"""
    print("格式化代码...")
    subprocess.run([sys.executable, "-m", "black", "."])
    subprocess.run([sys.executable, "-m", "isort", "."])


def run_lint():
    """检查代码质量"""
    print("检查代码质量...")
    subprocess.run([sys.executable, "-m", "flake8", "."])
    subprocess.run([sys.executable, "-m", "mypy", "."])


def main():
    parser = argparse.ArgumentParser(description="MinerU文档解析系统管理脚本")
    
    subparsers = parser.add_subparsers(dest="command", help="可用命令")
    
    # API服务器
    api_parser = subparsers.add_parser("api", help="启动API服务器")
    api_parser.add_argument("--host", default="0.0.0.0", help="服务器地址")
    api_parser.add_argument("--port", type=int, default=8000, help="服务器端口")
    api_parser.add_argument("--debug", action="store_true", help="调试模式")
    
    # MCP服务器
    mcp_parser = subparsers.add_parser("mcp", help="启动MCP服务器")
    mcp_parser.add_argument("--port", type=int, default=8001, help="服务器端口")
    
    # 初始化
    init_parser = subparsers.add_parser("init", help="初始化系统")
    
    # 测试
    test_parser = subparsers.add_parser("test", help="运行测试")
    
    # 代码格式化
    format_parser = subparsers.add_parser("format", help="格式化代码")
    
    # 代码检查
    lint_parser = subparsers.add_parser("lint", help="检查代码质量")
    
    # 开发模式
    dev_parser = subparsers.add_parser("dev", help="开发模式")
    
    args = parser.parse_args()
    
    if args.command == "api":
        if args.host or args.port or args.debug:
            # 更新配置
            from core.config import get_settings
            settings = get_settings()
            if args.host:
                settings.host = args.host
            if args.port:
                settings.port = args.port
            if args.debug:
                settings.debug = True
        
        run_api_server()
    
    elif args.command == "mcp":
        if args.port:
            from core.config import get_settings
            settings = get_settings()
            settings.mcp_port = args.port
        run_mcp_server()
    
    elif args.command == "init":
        run_init()
    
    elif args.command == "test":
        run_tests()
    
    elif args.command == "format":
        run_format()
    
    elif args.command == "lint":
        run_lint()
    
    elif args.command == "dev":
        print("开发模式启动...")
        print("启动API服务器...")
        # 这里可以启动多个服务
        run_api_server()
    
    else:
        parser.print_help()


if __name__ == "__main__":
    main()